const app = getApp()
var queryUrl = app.globalData.queryUrl;
var QQMapWX = require('../../../utils/qqmap-wx-jssdk.min.js');
var qqmapsdk;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    videoDetail: '',
    start: 0,
    current: 0,
    startTouch: '',
    startNum: '0',
    //其中的 视频url(videoUrl) 封面url(videoImageUrl) 头像url(headUrl) 的话大家自己填上就行
    videoList: [], //接口返回的视频列表。
    touch: false,
    touchStartTime: 0, //触摸开始时间
    touchEndTime: 0, // 触摸结束时间
    lastTapTime: 0, // 单击事件点击后要触发的函数
    lastTapTimeoutFunc: null,
    switchTo: true,
    page: 1,
    percent: 0,
    autoplay: true,
    play: false,
    gps: false,
    longitude: '', //钟楼
    latitude: '', //钟楼
    user:{},
    city:'',
    talkAll:''//评论
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.videoContext = wx.createVideoContext('videoplayer');
    this.setData({
      updateState: true
    })
  },
  

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    qqmapsdk = new QQMapWX({
      key: 'USJBZ-3LH6D-JWD4K-PYRYA-3DR32-SMBVJ' // 必填
    });
    try {
      var openId = wx.getStorageSync('openId')
      if (openId) {
        that.setData({
          openId: openId
        })
        var user = wx.getStorageSync('user')
        if (user) {
          that.setData({
            user: user
          })
          //查询是否点赞当前视频
          wx.request({
            url: queryUrl + 'video/praise',
            method: 'get',
            data: {
              userId: that.data.user.id,
              shopId: newVsrc[index].id
            },
            success: function (res) {
              //提示用户
              wx.showToast({
                title: '取消点赞',
                icon: 'none'
              })
            },
          })
        }
      }
      else {
        wx.login({
          success: function (res) {
            var code = res.code;
            if (code) {
              wx.request({
                url: queryUrl + 'auth/getOpenId',
                data: { code: code },
                success: function (res1) {
                  try {
                    that.setData({
                      openId: res1.data.openId
                    })
                    wx.setStorageSync('openId', res1.data.openId);
                    console.log('storage openId:' + wx.getStorageSync('openId'));
                    //检测用户是否已注册
                    if (res1.data.openId != '') {
                      wx.request({
                        url: queryUrl + 'auth/index',
                        data: { openId: res1.data.openId },
                        success: function (res2) {
                          //更新本页面shopCode
                          that.setData({
                            user: res2.data.user
                          })
                          //更新缓存shopCode
                          try {
                            wx.setStorageSync('user', res2.data.user);
                          }
                          catch (e) {
                          }
                        }
                      })
                    }
                  }
                  catch (e) {
                  }
                }
              })
            } else {
              console.log('获取用户登录态失败：' + res.errMsg);
            }
          }
        });
      }
    } catch (e) {
    }
    // that.getVideoList();
    //获取当前位置信息
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        console.log(res)
        that.setData({
          longitude: res.longitude,
          latitude: res.latitude,
          gps: true
        })

        that.getLocal()
      }
    })
    console.log(that.data.user)
    that.setData({ page: 1 })
    that.getVideoList(that.data.page);
    //wx.clearStorageSync()
  },
  // 获取当前地理位置
  getLocal: function () {
    let vm = this;
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: vm.data.latitude,
        longitude: vm.data.longitude
      },
      success: function (res) {
      
        let city = res.result.ad_info.city
        vm.setData({
          city: city,
        })
        console.log(vm.data.city)
      },
      fail: function (res) {
        console.log(res);
      },
      complete: function (res) {
        // console.log(res);
      }
    });
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  // 下面主要模仿滑动事件
  touchstart: function (e) {
    console.log(e);
    this.setData({
      // touchStartTime: e.timeStamp,
      showGuide: false
    })
    let startTouch = e.changedTouches[0]
    this.setData({
      startTouch: startTouch,
      touch: false
    })
  },
  touchmove: function (e) {
    let Y = e.changedTouches[0].pageY - this.data.startTouch.pageY;
  },
  touchend: function (e) {
    // this.setData({
    //   touchEndTime: e.timeStamp
    // })
    var that = this;

    if (Math.abs(e.changedTouches[0] - e.changedTouches[0]) < 40) {
      that.videoContext = wx.createVideoContext('videoplayer')
      if (!that.data.play) {
        //暂停播放
        that.videoContext.pause()//暂停播放
        that.setData({
          play: true
        })
      } else {
        //当play==false 显示图片 开始播放
        that.videoContext.play()//开始播放
        that.setData({
          play: false
        })
      }
    }
    console.log(that.data.startTouch + '----' + e.changedTouches[0]);
    that.getDirect(that.data.startTouch, e.changedTouches[0])
  },
  touchcancel: function (e) {
    this.getDirect(this.data.startTouch, e.changedTouches[0])
  },
  // 计算滑动方向
  getDirect: function (start, end) {
    console.log(start.pageY + '----' + end.pageY);
    var X = end.pageX - start.pageX,
      Y = end.pageY - start.pageY;

    if (Math.abs(X) > Math.abs(Y) && X > 0) {
      console.log("left 2 right");
    }
    else if (Math.abs(X) > Math.abs(Y) && X < 0) {
      console.log("right 2 left");
    }
    else if (Math.abs(Y) > Math.abs(X) && Y > 40) {
      if (this.data.current > 0) {
        this.setData({
          touch: true,
          transitionOver: false
        })
        this.pre()
      } else {
        this.setData({
          current: 0
        })
      }
    }
    else if (Math.abs(Y) > Math.abs(X) && Y < -40) {
      if (this.data.current < this.data.videoList.length - 2) {
        this.setData({
          touch: true
        })
        this.next()
      }else if(this.data.current == this.data.videoList.length - 1){
          wx.showToast({
            title: '没有更多视频了！',
            icon: 'none'
          })
          return false
      }
       else {
        this.getVideoList(this.data.page);
        this.setData({
          current: this.data.videoList.length - 1
        })
      }
    }
  },
  // 播放上一个
  pre: function () {
    this.setData({
      current: this.data.current - 1,
      play: false
    })
    console.log(this.data.current)
  },

  // 播放下一个
  next: function () {
    var that = this;
    console.log('current:' + that.data.current + '-----videolist-length:' + that.data.videoList.length)
    

    this.setData({
      current: this.data.current + 1,
      play: false
    })
    console.log(that.data.current)
  },
  //点击暂停/开始
  videoTap: function () {
    //获取video
    this.videoContext = wx.createVideoContext('videoplayer')
    if (this.data.play) {
      //开始播放
      this.videoContext.play()//开始播放
      this.setData({
        play: false
      })
    } else {
      //当play==false 显示图片 暂停
      this.videoContext.pause()//暂停播放
      this.setData({
        play: true
      })
    }
  },
  //播放条时间改表触发
  videoUpdate(e) {
    // if (this.data.updateState) { //判断拖拽完成后才触发更新，避免拖拽失效
    //   let sliderValue = e.detail.currentTime / e.detail.duration * 100;
    //   this.setData({
    //     sliderValue: sliderValue,
    //     duration: e.detail.duration
    //   })
    // }
    var val = e.detail.currentTime;
    var max = e.detail.duration;
    var percent = Math.round(val / max * 10000) / 100;
    this.setData({ percent: percent })
  },
  sliderChanging(e) {
    this.setData({
      updateState: false //拖拽过程中，不允许更新进度条
    })
  },
  //拖动进度条触发事件
  sliderChange(e) {
    if (this.data.duration) {
      this.videoContext.seek(e.detail.value / 100 * this.data.duration);
      //完成拖动后，计算对应时间并跳转到指定位置
      this.setData({
        sliderValue: e.detail.value,
        updateState: true //完成拖动后允许更新滚动条
      })
    }
  },
  getVideoList: function (page) {
    console.log('page:----' + this.data.page)
    var that = this;
    var totalNum = this.data.totalNum;
    wx.request({
      url: queryUrl + 'video/index',
      data: {
        page: that.data.page, 
        type: 1, 
        longitude: that.data.longitude,
        latitude: that.data.latitude,
        userId: that.data.user.id },
      success: function (res) {
        console.log(res);
        var videoList = res.data.video;
        if(res.data.video.length == 0){
          return;
        }else{
          var videoList = that.data.videoList.concat(videoList)
          totalNum = videoList.length;
          that.setData({
            videoList: videoList,
            totalNum: totalNum,
            page: that.data.page + 1
          })
        }
        
      }
    })
  },
  // 点赞
  handle: function (e) {
    let that = this
    let index = e.currentTarget.dataset.index
    let newVsrc = that.data.videoList
    console.log(newVsrc)
    if (newVsrc[index].praise == 1) {
      newVsrc[index].praise = null //取赞
      wx.request({
        url: queryUrl + 'video/praiseDelete',
        method: 'post',
        data: {
          userId: that.data.user.id,
          videoId: newVsrc[index].id
        },
        success: function (res) {
          //提示用户
          wx.showToast({
            title: '取消点赞',
            icon: 'none'
          })
        },
      })

    } else {
      newVsrc[index].praise = 1 //点赞
      wx.request({
        url: queryUrl + 'video/praiseAdd',
        method: 'post',
        data: {
          userId: that.data.user.id,
          videoId: newVsrc[index].id
        },
        success: function (res) {
          console.log(res)
        },
      })
      //提示用户
      wx.showToast({
        title: '点赞成功',
        icon: 'none'
      })
    }
    that.setData({
      videoList: newVsrc
    })
  },
  // 关注
  clickAdd: function (e) {
    let that = this
    let index = e.currentTarget.dataset.index
    let newVsrc = that.data.vsrc
    console.log(index)
    if (newVsrc[index].follow == null) {
      newVsrc[index].follow = 1
      try {
        var openId = wx.getStorageSync('openId')
      } catch (e) { }
      wx.request({
        url: queryUrl + 'registerFav',
        data: {
          opendId: that.data.opendId,
          shopId: 1
        },
        method: "post",
        success: function (res) {
          console.log(res)
        }
      })
    }
    that.setData({
      vsrc: newVsrc
    })
  },
  //显示对话框
  showModal: function () {
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
      showModalStatus: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 0)
  },
  //点击我显示底部弹出框
  clickme: function (e) {
    let that = this
    let index = e.currentTarget.dataset.index
    let newVsrc = that.data.videoList
    this.showModal();
    wx.request({
      url: queryUrl + 'comment/index',
      data: {
        videoId: newVsrc[index].id
      },
      success: function (res) {
        console.log(res.data)
        that.setData({
          talkAll: res.data.comment
        })
      }
    })
  },
  //隐藏对话框
  hideModal: function () {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showModalStatus: false
      })
    }.bind(this), 200)
  },
  /**跳转到发视频者个人详情 */
  imgGo: function (e) {
    var that = this
    var shopId = e.currentTarget.dataset.shopid; //传参数到另一个页面
    var follow = e.currentTarget.dataset.follow
    var longitude = that.data.longitude
    var latitude = that.data.latitude
    console.log('shopId:' + shopId )
    //console.log(follow)
    wx.navigateTo({
      url: '../head/head?shopId=' + shopId + '&follow=' + follow + '&longitude=' + longitude + '&latitude=' + latitude,
    })
  },
})